package cn.pconline.autoclub.web;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.ClubPhoto;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.Photo;
import cn.pconline.autoclub.entity.PhotoPraise;
import cn.pconline.autoclub.entity.PhotoReply;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.CensorPhotoReplyService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.PagerService;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.autoclub.service.PhotoPraiseService;
import cn.pconline.autoclub.service.PhotoReplyService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.LastestPhoto;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.YearMonth;
import cn.pconline.autoclub.util.dyna.AbstractDyna;
import cn.pconline.autoclub.util.dyna.CommentDynaUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/album")
public class AlbumController {

    @Autowired
    private AlbumService albumService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private PhotoPraiseService photoPraiseService;
    @Autowired
    private PhotoReplyService photoReplyService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private CensorPhotoReplyService censorPhotoReplyService;
    @Autowired
    private PagerService pagerService;
    @Autowired
    private PetrolService petrolService;
    private final static int DEFAULT_PAGE_SIZE = 20;
    /**
     * 点赞弹框默认每页数*
     */
    private static final int DEFAULT_PRAISE_PAGE_SIZE = 15;
    /**
     * 发表动态超多9张图片*
     */
    private static final int DEFAULT_MAX_IMAGE_SIZE = 9;
    protected static final Logger log = LoggerFactory.getLogger(AlbumController.class);
    /**
     * 作者头像50X50*
     */
    private static final int DEFAULT_AUTHORPHOTO_SIZE = 50;//作者头像50X50
    private static final int DEFAULT_PAGE_NUM_DETAIL = 1;//图片终端页默认点赞页码
    private static final int DEFAULT_PAGE_SIZE_DETAIL = 6;//图片终端页默认点赞页数

    /**
     * 返回信息
     *
     * @param resp
     * @param success
     * @param message
     * @throws Exception
     */
    private void responseText(HttpServletResponse resp, boolean success, String... message) {
        try {
            resp.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("success", success)
                    .put("message", message)
                    .toString());
        } catch (IOException ex) {
            log.error("responseText fail!", ex);
        }
    }

    private void printMsg(HttpServletResponse response, String str, String callback) {
        try {
            PrintWriter writer = response.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                writer.print(callback + "(" + str + ")");
            } else {
                writer.print(str);
            }
            writer.flush();
            writer.close();
        } catch (IOException ex) {
        }
    }

    private void printSuccessMsg(HttpServletResponse resp, String msg, JSONObject data, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", AppUtils.STATUS_OK);
        if (StringUtils.isNotEmpty(msg)) {
            json.put("message", msg);
        }
        if (data != null) {
            json.put("data", data);
        }
        printMsg(resp, json.toJSONString(), callback);
    }

    private void printErrorMsg(HttpServletResponse resp, String msg, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", AppUtils.STATUS_FAIL);
        json.put("message", msg);
        printMsg(resp, json.toJSONString(), callback);
    }

    /**
     * 判断用户是否登录 》》 是否是会员
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    private boolean authFilter(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);

        // 用户是否登录
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) { // 未登录
            try {
                String url = systemConfig.getUcRoot() + "/login.jsp?return=" + request.getRequestURL();
                if (request.getQueryString() != null) {
                    url += "?" + request.getQueryString();
                }
                response.sendRedirect(url);
            } catch (IOException ex) {
                log.error("authFilter fail!", ex);
            }
            return false;
        }

        // 会员
        if (!memberService.isClubMember(user.getUid(), clubId)) {
            try {
                response.sendError(403);
            } catch (IOException ex) {
                log.error("authFilter fail!", ex);
            }
            return false;
        }

        return true;
    }

    /**
     * 是否有权限 登录》》会员
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/hasRight.do", method = RequestMethod.POST)
    public String hasRight(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        // 用户是否登录
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) { // 未登录
            this.responseText(response, false, "您还未登录，请登录后再操作");
            return null;
        }

        // 会员
        if (!memberService.isClubMember(user.getUid(), clubId)) {
            this.responseText(response, false, "您不是本车友会会员，请加入本车友会");
            return null;
        }
        this.responseText(response, true);
        return null;
    }

    /**
     * 弹框信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/message.do", method = RequestMethod.GET)
    public String message(HttpServletRequest request) {

        request.setAttribute("message", WebUtils.param(request, "message", ""));

        return "/template/album/message";
    }

    /**
     * 相册管理列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/album.do", method = RequestMethod.GET)
    public String album(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        if (club == null || pageNo < 1) {
            try {
                response.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidClub!", e);
            }
        }
        User user = userAuth.getUser(request, response);
        long uid = user.getUid();
        boolean isLogin = memberService.isClubMember(uid, clubId);

        boolean isAdmin = memberService.isClubNormalAdmin(uid, clubId);

        int total = albumService.countAlbumByClubId(clubId); //计算总相册数
        //计算总页数
        int totalPageCount = (total == 0 || DEFAULT_PAGE_SIZE <= 0) ? 1 : total / DEFAULT_PAGE_SIZE + (total % DEFAULT_PAGE_SIZE == 0 ? 0 : 1);
        //如果pageNo大于最大页数则取最后一页的数据
        if (pageNo > totalPageCount) {
            try {
                response.sendRedirect(systemConfig.getRoot() + "/" + club.getClubUrl() + "/album/" + totalPageCount + "/");
            } catch (IOException ex) {
            }
            return null;
        }
        Pager<Album> pager = albumService.pagerAllAlbumByClubId(clubId, DEFAULT_PAGE_SIZE, pageNo);
        albumService.loadPhotoByAlbumsLimit(pager.getResultList(), 4);
        request.setAttribute("club", club);
        request.setAttribute("pager", pager);
        request.setAttribute("clubId", clubId);
        request.setAttribute("currentUser", uid);
        request.setAttribute("isAdmin", isAdmin);
        request.setAttribute("isLogin", isLogin);
        request.setAttribute("timestamp", System.currentTimeMillis());
        ClubController.setClubStyle(request, clubId);
        return "/template/album/album";
    }

    /**
     * 添加或修改页面跳转
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/addAlbum.do", method = RequestMethod.GET)
    public String addAlbum(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            try {
                response.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidClub!", e);
            }
        }
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        String name = WebUtils.param(request, "name", "");

        request.setAttribute("clubId", clubId);
        request.setAttribute("club", club);
        request.setAttribute("albumId", albumId);
        request.setAttribute("name", name);
        response.setHeader("Cache-Control", "no-cache");

        return "/template/album/album_add";
    }

    /**
     * 新增或修改相册信息
     *
     * @param resp
     * @param req
     * @return
     */
    @RequestMapping(value = "/saveAlbum.do", method = RequestMethod.POST)
    public String saveAlbum(HttpServletResponse resp, HttpServletRequest req) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        if (clubService.getValidClub(clubId) == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidClub!", e);
            }
        }
        String name = WebUtils.param(req, "name", "").trim();
        if (StringUtils.isBlank(name)) {
            this.responseText(resp, false, "相册名称不能为空");
            return null;
        } else if (!name.matches(Regex.chineseNumAbc.value)) {
            this.responseText(resp, false, "请输入汉字、数字或者字母");
            return null;
        } else if (name.length() > 20) {
            this.responseText(resp, false, "请使用长度为1～20个字符的数字、字母或者汉字");
            return null;
        }

        if (!authFilter(req, resp)) {
            return null;
        }

        User user = userAuth.getUser(req, resp);
        Date date = DateUtils.getNow();
        Album album;
        if (albumId == 0) { // 新增
            album = new Album();
            album.setClubId(clubId);
            album.setCover("http://www1.pcauto.com.cn/bbs/cargroup/2014/images/defaultphoto.png");
            album.setCreateBy(user.getUid());
            album.setCreateAt(date);
        } else { // 更新
            album = albumService.getValidAlbum(albumId);
            if (album == null) {
                this.responseText(resp, false, "数据异常,该相册不存在!");
                return null;
            }

            if (!albumOperateAuth(album.getCreateBy(), clubId, user.getUid())) { // 不是会长
                this.responseText(resp, false, "您不是会长或该相册创建者!");
                return null;
            }
        }

        album.setName(name);
        album.setUpdateAt(date);

        boolean success = true;
        try {
            albumService.updateOrSave(album);
        } catch (DuplicateKeyException ex) {
            success = false;
        } catch (Exception e) {
            success = false;
        }
//        this.responseText(resp, success);
        try {
            resp.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("success", success)
                    .put("albumId", album.getAlbumId())
                    .toString());
        } catch (IOException ex) {
            log.error("responseText fail!", ex);
        }

        resp.setHeader("Cache-Control", "no-cache");
        return null;
    }

    /**
     * 删除相册页面跳转
     *
     * @param request
     * @param resp
     * @return
     */
    @RequestMapping(value = "/removeAlbum.do", method = RequestMethod.GET)
    public String delAlbum(HttpServletRequest request, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        Album album = albumService.getAlbumById(albumId);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            this.responseText(resp, false, "数据异常,车友会不存在!");
            return null;
        }
        if (albumId < 1 || album == null) {
            this.responseText(resp, false, "数据异常,该相册不存在!");
            return null;
        }

        request.setAttribute("clubId", clubId);
        request.setAttribute("club", club);
        request.setAttribute("albumId", albumId);
        request.setAttribute("quantity", album.getQuantity());
        request.setAttribute("timestamp", System.currentTimeMillis());

        return "/template/album/album_delete";
    }

    /**
     * 删除相册
     *
     * @param resp
     * @param req
     * @return
     */
    @RequestMapping(value = "/delAlbum.do", method = RequestMethod.POST)
    public String delAlbum(HttpServletResponse resp, HttpServletRequest req) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        Album album = albumService.getValidAlbum(albumId);
        if (clubService.getValidClub(clubId) == null) {
            this.responseText(resp, false, "数据异常,车友会不存在!");
            return null;
        }
        if (albumId < 1 || album == null) {
            this.responseText(resp, false, "数据异常,该相册不存在!");
            return null;
        }
        if (album.getClubId() != clubId) {
            this.responseText(resp, false, "您不是该车友会用户，无权操作");
            return null;
        }
        if (album.getIsDefault() == Album.ISDEFAULT_YES) {
            this.responseText(resp, false, "默认相册不能删除!");
            return null;
        }

        if (!authFilter(req, resp)) {
            return null;
        }
        User user = userAuth.getUser(req, resp);
        if (!albumOperateAuth(album.getCreateBy(), clubId, user.getUid())) { // 不是会长
            this.responseText(resp, false, "您不是会长或该相册创建者!");
            return null;

        }
        try {
            List<Photo> photos = albumService.getAllPhotosByAlbumId(albumId);
            List<ClubPhoto> clubPhotos = new ArrayList<ClubPhoto>(photos.size());
            for (Photo photo : photos) {
                photo.setUpdateAt(DateUtils.getNow());
                photo.setStatus(Photo.STATUS_DELETE);
                albumService.updatePhoto(photo);

                ClubPhoto clubPhoto = new ClubPhoto();
                clubPhoto.setAlbumId(photo.getAlbumId());
                clubPhoto.setClubId(clubId);
                clubPhoto.setStatus(ClubPhoto.STATUS_DELETE);
                clubPhoto.setPhotoId(photo.getPhotoId());
                clubPhotos.add(clubPhoto);
            }

            album.setStatus(Album.STATUS_DELETE);
            albumService.update(album);

            albumService.deleteClubPhotos(clubPhotos);

            //某相册被会长删除，通知相册创建者
            if (memberService.isClubNormalAdmin(user.getUid(), clubId) && user.getUid() != album.getCreateBy()) {//会长删除相册
                User receiver = userService.findUser(album.getCreateBy());
                messageService.send(receiver, MessageService.DELETE_ALBUM,
                        album.getName(), messageService.assembleUserUrl(user.getUid(), user.getNickname()));
            }

        } catch (Exception e) {
            log.error("delAlbum fail!", e);
            this.responseText(resp, false, "数据出错");
        }


        this.responseText(resp, true);
        resp.setHeader("Cache-Control", "no-cache");

        return null;
    }

    /**
     * 相片列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/photo.do", method = RequestMethod.GET)
    public String photo(HttpServletRequest request, HttpServletResponse response) {
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Album album = albumService.getValidAlbum(albumId);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        Club club = clubService.getValidClub(clubId);
        if (club == null || albumId < 1 || album == null || pageNo < 1) {
            try {
                response.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidClub!", e);
            }
        }
        User user = userAuth.getUser(request, response);
        boolean isLogin = memberService.isClubMember(user.getUid(), clubId);
        if (user.getUid() != 0L) {
            ClubMember clubMember = memberService.findMember(user.getUid(), clubId);
            request.setAttribute("loginClubMember", clubMember);
        }
        boolean isRight = false;
        List<Album> albums = null;
        Pager<Photo> pager = null;
        if (album != null) {
            albums = albumService.getAllAlbumsByClubId(clubId, albumId);

            int pageCount = albumService.countAlbumPhotoPagerNum(album.getAlbumId(), DEFAULT_PAGE_SIZE);
            if (pageNo > pageCount) {
                try {
                    response.sendRedirect(systemConfig.getRoot() + "/" + club.getClubUrl() + "/album/a" + album.getAlbumId() + "-photo/" + pageCount + "/");
                } catch (IOException ex) {
                }
                return null;
            }
            pager = albumService.pagerAllPhotosByAlbumId(albumId, DEFAULT_PAGE_SIZE, pageNo);
            //WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());

            isRight = memberService.isClubNormalAdmin(user.getUid(), album.getClubId()) || (album.getCreateBy() == user.getUid());
        }

        request.setAttribute("pager", pager);
        request.setAttribute("myUrl", club.getClubUrl());
        request.setAttribute("club", club);
        request.setAttribute("isRight", isRight);
        request.setAttribute("albums", albums);
        request.setAttribute("albumId", albumId);
        request.setAttribute("isLogin", isLogin);
        request.setAttribute("timestamp", System.currentTimeMillis());
        request.setAttribute("loginUser", user);

        long createBy = album.getCreateBy();
        User createUser = userService.findUser(createBy);

        if (createUser == null) { //如果创建者为null则相册的创建者默认为会长
            ClubMember clubMember = memberService.findAdminByClubId(clubId);
            createUser = userService.findUser(clubMember.getUid());
            album.setCreateBy(createUser.getUid());
        }

        request.setAttribute("album", album);
        request.setAttribute("nickName", createUser.getNickname());

        ClubController.setClubStyle(request, club.getClubId());
        ClubController.setClubStyle(request, club.getClubId());
        return "/template/album/photo";
    }

    /**
     * 相片详细页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/photoDetail.do", method = RequestMethod.GET)
    public String photoDetail(HttpServletRequest request, HttpServletResponse response) {

        long photoId = WebUtils.paramLong(request, "photoId", 0);
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        Album album = albumService.getValidAlbum(albumId);
        Photo photo = albumService.getValidPhoto(photoId, albumId);
        //为相册、照片相关属性赋值，防止抛空指针
        long clubId = 0;
        if (album != null) {
            clubId = album.getClubId();
        }
        Club club = clubService.getValidClub(clubId);
        if (photoId < 1 || albumId < 1 || album == null || club == null || photo == null) {
            try {
                response.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail!", e);
            }
        }
        User user = userAuth.getUser(request, response);
        request.setAttribute("user", user);
        request.setAttribute("avatar", WebUtils.face(user.getUid(), DEFAULT_AUTHORPHOTO_SIZE));
        request.setAttribute("isLogin", user.getUid() > 0);
        request.setAttribute("album", album);
        request.setAttribute("photo", photo);
        request.setAttribute("club", club);
        return "/template/album/photo_detail";
    }

    /**
     * 上传图片页面跳转
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/upload.do", method = RequestMethod.GET)
    public String upload(HttpServletRequest request, HttpServletResponse response) {

        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getClub(clubId);
        long albumId = WebUtils.paramLong(request, "albumId", 0);

        Album album = null;
        if (albumId == 0) {
            album = albumService.getDefaultAlbum(clubId);
        } else {
            album = albumService.getAlbumById(albumId);
        }
        if (clubService.getValidClub(clubId) == null) {
            try {
                response.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidClub!", e);
            }
        }
        if (!authFilter(request, response)) {
            return null;
        }

        request.setAttribute("clubId", clubId);
        request.setAttribute("club", club);
        request.setAttribute("album", album);
        request.setAttribute("albumId", albumId);
        request.setAttribute("timestamp", System.currentTimeMillis());
        request.setAttribute("listOptions", albumService.getAllAlbumsByClubId(clubId, 0));
        ClubController.setClubStyle(request, clubId);
        return "/template/album/photo_upload";
    }

    /**
     * 上传相片
     *
     * @param resp
     * @param req
     * @return
     */
    @RequestMapping(value = "/uploadPhotos.do", method = RequestMethod.POST)
    @ResponseBody
    public void uploadPhotos(HttpServletResponse resp, HttpServletRequest req) {
        //动态的content 存放数量{pictureNum:0}
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        JSONArray picsArray = WebUtils.parseArray(req, "images");
        Album album = albumService.getValidAlbum(albumId);
        JSONObject jsonObject = new JSONObject();
        JSONObject successObject = new JSONObject(); //成功发表的动态
        JSONArray successImgs = new JSONArray();
        if (albumId < 1 || album == null) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "数据异常,该相册不存在!");
            this.printMsg(resp, jsonObject.toJSONString(), callback);
            return;
        }
        User user = userAuth.getUser(req, resp);
        if (user == null || user.getUid() <= 0) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "用户未登录，请先登录!");
            this.printMsg(resp, jsonObject.toJSONString(), callback);
            return;
        }
        if (!memberService.isClubMember(user.getUid(), clubId)) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "不是该车友会会员，无权操作!");
            this.printMsg(resp, jsonObject.toJSONString(), callback);
            return;
        }
        if (picsArray == null || picsArray.size() <= 0) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "请先上传图片!");
            this.printMsg(resp, jsonObject.toJSONString(), callback);
            return;
        }
        try {
            String cover = "";
            List<Photo> list = new ArrayList<Photo>();
            for (int i = 0; i < picsArray.size(); i++) {
                JSONObject o = JSONObject.parseObject(picsArray.getString(i));
                String url = o.getString("url");
                if (i == 0) {
                    cover = url;
                }
                Photo photo = new Photo();
                photo.setName(o.getString("name"));
                photo.setUrl(o.getString("url"));
                photo.setAlbumId(albumId);
                photo.setCreateBy(user.getUid());
                photo.setWidth(o.getInteger("width"));
                photo.setHeight(o.getInteger("height"));
                list.add(photo);
            }
            long[] ids = albumService.batchCreatePhotos(albumId, list);
            //成功生成车友会最新上传相片
            if (ids.length > 0) {
                List<ClubPhoto> clubPhotos = new ArrayList<ClubPhoto>(ids.length);
                for (long id : ids) {
                    ClubPhoto clubPhoto = new ClubPhoto();
                    clubPhoto.setAlbumId(albumId);
                    clubPhoto.setClubId(clubId);
                    clubPhoto.setPhotoId(id);
                    clubPhoto.setCreateAt(new Date());
                    clubPhoto.setCreateBy(user.getUid());
                    clubPhoto.setStatus(ClubPhoto.STATUS_NORMAL);
                    clubPhotos.add(clubPhoto);
                }
                albumService.batchCreateClubPhoto(clubId, clubPhotos);
            }
            synchronized (album) {
                albumService.refshAlbumPhotos(albumId, cover);
            }

            //创建图片动态
            List<DynaImage> dynaImages = new ArrayList<DynaImage>();
            if (picsArray != null) {
                for (int i = 0; i < picsArray.size(); i++) {
                    JSONObject o = JSONObject.parseObject(picsArray.getString(i));
                    DynaImage dynaImage = new DynaImage();
                    dynaImage.setSeq(i + 1);// 车友会的图片的seq跟论坛的图片的seq都统一从1开始
                    dynaImage.setUrl(o.getString("url"));
                    dynaImage.setWidth(o.getInteger("width"));
                    dynaImage.setHeight(o.getInteger("height"));
                    dynaImages.add(dynaImage);
                    if (i < DynaController.DEFAULT_MAX_IMAGE_SIZE) {
                        JSONObject d = dynaImage.toJSONObject();
                        String url;
                        if (picsArray.size() > 1) {
                            url = dynaImage.getUrl120x80();
                        } else {
                            url = (dynaImage.getUrl240x160());
                        }
                        d.put("url", url);
                        successImgs.add(d);
                    }
                }
            }
            Date cur = DateUtils.getNow();
            AbstractDyna dyna = new AbstractDyna();
            dyna.setClubId(clubId);
            dyna.setContent("{pictureNum:" + list.size() + "}");
            dyna.setCreateBy(user.getUid());
            dyna.setCreateName(user.getNickname() != null ? user.getNickname() : user.getUsername());
            dyna.setCreateDate(cur);
            dyna.setTargetId(albumId);
            long dynaId = dynaService.createPictureDyna(dyna, dynaImages);
            jsonObject.put("code", AppUtils.STATUS_OK);
            //组装成功发表后对象（用于首页js刷新）
            successObject.put("content", "");
            successObject.put("albumId", albumId);
            successObject.put("albumName", album.getName());
            successObject.put("pictureNum", picsArray.size());
            successObject.put("type", DynaInfo.TYPE_PICTURE);
            successObject.put("templateId", "template-pictureDyna");
            successObject.put("avatar", WebUtils.face(dyna.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
            successObject.put("nickName", userService.findUser(dyna.getCreateBy()).getNickname());
            successObject.put("userId", dyna.getCreateBy());
            successObject.put("dynaInfoId", dynaId);
            successObject.put("year", DateUtils.format(dyna.getCreateDate(), "yyyy"));
            successObject.put("createDate", DateUtils.format(dyna.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
            successObject.put("fmtCreateDate", DateUtils.format(dyna.getCreateDate(), "MM-dd HH:mm:ss"));
            successObject.put("praiseCount", 0);	//	刚发表点赞数默认为0
            successObject.put("postCount", 0);		//  刚发表回复数默认为0
            successObject.put("images", successImgs);
            jsonObject.put("data", successObject);
            this.printMsg(resp, jsonObject.toJSONString(), callback);
        } catch (Exception e) {
            log.error("post picDyna --uploadPhotos!", e);
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "系统出错，请联系管理员!");
            this.printMsg(resp, jsonObject.toJSONString(), callback);
        }
    }

    /**
     * 创建图片动态信息
     *
     * @param resp
     * @param req
     * @return
     */
    @RequestMapping(value = "/createPhotosDyna.do", method = RequestMethod.POST)
    public void createPhotosDyna(HttpServletResponse resp, HttpServletRequest req) {
        JSONObject jsonObject = new JSONObject();
        JSONObject successObject = new JSONObject();
        String callback = "";
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        JSONArray picsArray = WebUtils.parseArray(req, "images");
        JSONArray successImgs = new JSONArray();

        Album album = albumService.getValidAlbum(albumId);
        if (albumId < 1 || album == null) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "数据异常,该相册不存在!");
            this.printMsg(resp, jsonObject.toJSONString(), callback);
            return;
        }

        User user = userAuth.getUser(req, resp);
        if (user == null || user.getUid() <= 0) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "用户未登录，请先登录!");
            this.printMsg(resp, jsonObject.toJSONString(), callback);
            return;
        }

        if (!memberService.isClubMember(user.getUid(), clubId)) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "不是该车友会会员，无权操作!");
            this.printMsg(resp, jsonObject.toJSONString(), callback);
            return;
        }

        if (picsArray == null || picsArray.size() <= 0) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "请先上传图片!");
            this.printMsg(resp, jsonObject.toJSONString(), "");
            return;
        }

        //创建图片动态
        List<DynaImage> dynaImages = new ArrayList<DynaImage>();
        if (picsArray != null) {
            for (int i = 0; i < picsArray.size(); i++) {
                JSONObject o = JSONObject.parseObject(picsArray.getString(i));
                DynaImage dynaImage = new DynaImage();
                dynaImage.setSeq(i + 1);// 车友会的图片的seq跟论坛的图片的seq都统一从1开始
                dynaImage.setUrl(o.getString("url"));
                dynaImage.setWidth(o.getInteger("width"));
                dynaImage.setHeight(o.getInteger("height"));
                dynaImages.add(dynaImage);
                if (i < DynaController.DEFAULT_MAX_IMAGE_SIZE) {
                    JSONObject d = dynaImage.toJSONObject();
                    String url;
                    if (picsArray.size() > 1) {
                        url = dynaImage.getUrl120x80();
                    } else {
                        url = (dynaImage.getUrl240x160());
                    }
                    d.put("url", url);
                    successImgs.add(d);
                }
            }
        }
        Date cur = DateUtils.getNow();
        AbstractDyna dyna = new AbstractDyna();
        dyna.setClubId(clubId);
        dyna.setContent("{pictureNum:" + picsArray.size() + "}");
        dyna.setCreateBy(user.getUid());
        dyna.setCreateName(user.getNickname() != null ? user.getNickname() : user.getUsername());
        dyna.setCreateDate(cur);
        dyna.setTargetId(albumId);
        long dynaId = dynaService.createPictureDyna(dyna, dynaImages);
        jsonObject.put("code", AppUtils.STATUS_OK);
        //组装成功发表后对象（用于首页js刷新）
        successObject.put("content", "");
        successObject.put("albumId", albumId);
        successObject.put("albumName", album.getName());
        successObject.put("pictureNum", picsArray.size());
        successObject.put("type", DynaInfo.TYPE_PICTURE);
        successObject.put("templateId", "template-pictureDyna");
        successObject.put("avatar", WebUtils.face(dyna.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
        successObject.put("nickName", userService.findUser(dyna.getCreateBy()).getNickname());
        successObject.put("userId", dyna.getCreateBy());
        successObject.put("dynaInfoId", dynaId);
        successObject.put("year", DateUtils.format(dyna.getCreateDate(), "yyyy"));
        successObject.put("createDate", DateUtils.format(dyna.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
        successObject.put("fmtCreateDate", DateUtils.format(dyna.getCreateDate(), "MM-dd HH:mm:ss"));
        successObject.put("praiseCount", 0);	//	刚发表点赞数默认为0
        successObject.put("postCount", 0);		//  刚发表回复数默认为0
        successObject.put("images", successImgs);
        jsonObject.put("data", successObject);
        this.printMsg(resp, jsonObject.toJSONString(), "");
    }

    /**
     * 上传相片
     *
     * @param resp
     * @param req
     * @return
     */
    @RequestMapping(value = "/uploadPhoto.do", method = RequestMethod.POST)
    public String uploadPhoto(HttpServletResponse resp, HttpServletRequest req) {
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        Album album = albumService.getValidAlbum(albumId);
        if (albumId < 1 || album == null) {
            this.responseText(resp, false, "数据异常,该相册不存在!");
            return null;
        }
        String name = WebUtils.param(req, "name", "");
        String url = WebUtils.param(req, "url", "");
        int width = WebUtils.paramInt(req, "width", 0);
        int height = WebUtils.paramInt(req, "height", 0);

        if (!authFilter(req, resp)) {
            return null;
        }
        User user = userAuth.getUser(req, resp);

        Date date = DateUtils.getNow();

        if (!url.endsWith(".jpg")) {
            this.responseText(resp, false, "图片格式不对");
            return null;
        }

        Photo photo = new Photo();
        photo.setName(name);
        photo.setUrl(url);
        photo.setAlbumId(albumId);
        photo.setCreateAt(date);
        photo.setUpdateAt(date);
        photo.setCreateBy(user.getUid());
        photo.setWidth(width);
        photo.setHeight(height);
        long photoId = albumService.create(photo);

        synchronized (album) {
            albumService.refshAlbumPhotos(albumId, url);
        }

        if (photoId > 0) {
            //上传图片生成车友会最新上传相片表数据
            ClubPhoto clubPhoto = new ClubPhoto();
            clubPhoto.setAlbumId(albumId);
            clubPhoto.setPhotoId(photoId);
            clubPhoto.setClubId(album.getClubId());
            clubPhoto.setCreateAt(new Date());
            clubPhoto.setCreateBy(user.getUid());
            clubPhoto.setStatus(ClubPhoto.STATUS_NORMAL);
            long id = albumService.createClubPhoto(clubPhoto);
            this.responseText(resp, true);
        } else {
            this.responseText(resp, false, "上传失败");
        }
        resp.setHeader("Cache-Control", "no-cache");

        return null;
    }

    /**
     * 删除相片页面跳转
     *
     * @param request
     * @param resp
     * @return
     */
    @RequestMapping(value = "/removePhotos.do", method = RequestMethod.GET)
    public String removePhotos(HttpServletRequest request, HttpServletResponse resp) {

        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        if (clubService.getValidClub(clubId) == null || albumId < 1 || albumService.getValidAlbum(albumId) == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidClub!", e);
            }
        }
        String message = WebUtils.param(request, "message", "");
        String photoIds = WebUtils.param(request, "photoIds", "");

        request.setAttribute("message", message);
        request.setAttribute("clubId", clubId);
        request.setAttribute("albumId", albumId);
        request.setAttribute("photoIds", photoIds);

        return "/template/album/photo_delete";
    }

    /**
     * 删除相片
     *
     * @param resp
     * @param req
     * @return
     * @
     */
    @RequestMapping(value = "/delPhotos.do", method = RequestMethod.POST)
    public String delPhotos(HttpServletResponse resp, HttpServletRequest req) {
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        if (clubService.getValidClub(clubId) == null || albumId < 1 || albumService.getValidAlbum(albumId) == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidClub!", e);
            }
        }
        String photoIds = WebUtils.param(req, "photoIds", "");

        if (!authFilter(req, resp)) {
            return null;
        }

        User user = userAuth.getUser(req, resp);

        String[] array = photoIds.split(",");
        String message = "";
        int size = array.length;
        List<Photo> photos = new ArrayList<Photo>(size);
        List<ClubPhoto> clubPhotos = new ArrayList<ClubPhoto>(size);
        Album album = albumService.getValidAlbum(albumId);
        if (album == null) {
            this.responseText(resp, false, "数据有误");
            return null;
        }

        for (String s : array) {
            long photoId = Long.parseLong(s);
            Photo photo = albumService.getValidPhoto(photoId, albumId);
            if (photo == null) {
                this.responseText(resp, false, "数据异常, 图片不存在!");
                return null;
            }

            if (!albumOperateAuth(photo.getCreateBy(), clubId, user.getUid())) { // 会长，副会长，上传者可以删除
                this.responseText(resp, false, "您无权限删除该相片");
                return null;

            }

            photo.setStatus(Photo.STATUS_DELETE);
            photos.add(photo);

            ClubPhoto clubPhoto = new ClubPhoto();
            clubPhoto.setAlbumId(albumId);
            clubPhoto.setClubId(clubId);
            clubPhoto.setStatus(ClubPhoto.STATUS_DELETE);
            clubPhoto.setPhotoId(photoId);
            clubPhotos.add(clubPhoto);
        }
        if (size != 0) {
            message = "删除成功!" + message;
            // 同个事务中更新图片
            albumService.updatePhotos(photos);
            //同个事物中删除车友会图片
            albumService.deleteClubPhotos(clubPhotos);
            // 更新相册的图片数量
            albumService.refshAlbumPhotos(albumId, "");

            this.responseText(resp, true, message);
        } else {
            message = "删除失败!" + message;
            this.responseText(resp, false, message);
        }
        resp.setHeader("Cache-Control", "no-cache");

        return null;
    }

    /**
     * 移动相片页面跳转
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "move.do", method = RequestMethod.GET)
    public String move(HttpServletRequest req, HttpServletResponse resp) {
        long moveAlbumId = WebUtils.paramLong(req, "moveAlbumId", 0);//移到新相册ID
        long albumId = WebUtils.paramLong(req, "albumId", 0);//原本相册ID
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        if (moveAlbumId < 1 || clubService.getValidClub(clubId) == null || albumId < 1
                || albumService.getValidAlbum(albumId) == null || albumService.getValidAlbum(moveAlbumId) == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail!", e);
            }
        }
        String message = WebUtils.param(req, "message", "");
        String photoIds = WebUtils.param(req, "photoIds", "");

        req.setAttribute("message", message);
        req.setAttribute("moveAlbumId", moveAlbumId);
        req.setAttribute("albumId", albumId);
        req.setAttribute("clubId", clubId);
        req.setAttribute("photoIds", photoIds);

        return "/template/album/photo_move";
    }

    /**
     * 移动相片
     *
     * @param req
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/movePhotos.do", method = RequestMethod.POST)
    public String movePhotos(HttpServletResponse resp, HttpServletRequest req) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        long moveAlbumId = WebUtils.paramLong(req, "moveAlbumId", 0);
        if (moveAlbumId < 1 || clubService.getValidClub(clubId) == null || albumId < 1
                || albumService.getValidAlbum(albumId) == null || albumService.getValidAlbum(moveAlbumId) == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail!", e);
            }

        }
        if (albumId == moveAlbumId) {
            this.responseText(resp, false, "移动失败, 无法移动到该相册");
            return null;
        }
        String photoIds = WebUtils.param(req, "photoIds", "");

        if (!authFilter(req, resp)) {
            return null;
        }
        User user = userAuth.getUser(req, resp);
        Album album = albumService.getValidAlbum(albumId);
        if (album == null) {
            this.responseText(resp, false, "数据异常, 该相册不存在!");
            return null;
        }
        if (!albumOperateAuth(album.getCreateBy(), clubId, user.getUid())) { // 不是会长
            this.responseText(resp, false, "您不是会长或该相册创建者!");
            return null;
        }
        Date date = DateUtils.getNow();

        long photoId;
        String[] array = photoIds.split(",");
        String message = "";
        boolean isMoveCover = false; // 是否作为封面的图片被移走
        int size = array.length;
        List<Photo> photos = new ArrayList<Photo>(size);
        for (String s : array) {
            photoId = Long.parseLong(s);
            Photo photo = albumService.getValidPhoto(photoId, albumId);
            if (photo == null) {
                this.responseText(resp, false, "数据异常, 图片不存在!");
                return null;
            }

            if (!albumOperateAuth(photo.getCreateBy(), clubId, user.getUid())) { // 不是图片上传者或会长
                message = "部分图片不是您上传的，无法移动!";
                size--;
                continue;
            }

            if (photo.getUrl().equals(album.getCover())) { // 作为封面的图片被移走
                isMoveCover = true;
            }

            photo.setUpdateAt(date);
            photos.add(photo);
        }

        if (size != 0) {
            Album moveAlbum = albumService.getValidAlbum(moveAlbumId);
            if (moveAndDeletePhoto(photos, moveAlbumId, moveAlbum.getClubId())) {
                message = "移动成功!" + message;

                int temp = album.getQuantity() - size;
                String albumCover = "http://www1.pcauto.com.cn/bbs/cargroup/2014/images/defaultphoto.png";
                if (isMoveCover) { // 作为封面的图片被移走
                    if (temp > 0) { // 设置为默认图片URL
                        List<Photo> li = albumService.listPhotosByAlbumId(album.getAlbumId(), 0, 1);
                        if (!li.isEmpty()) {
                            albumCover = li.get(0).getUrl();
                        }
                    }
                } else {
                    albumCover = album.getCover();
                }
                // 更新移除图片的相册的图片数量
                albumService.refshAlbumPhotos(albumId, albumCover);


                albumCover = photos.get(0).getUrl();
                // 更新移入图片的相册的图片数量
                albumService.refshAlbumPhotos(moveAlbumId, albumCover);
                this.responseText(resp, true, message);
            } else {
                message = "移动失败!" + message;
                this.responseText(resp, false, message);
            }
        } else {
            message = "移动失败!" + message;
            this.responseText(resp, false, message);
        }
        resp.setHeader("Cache-Control", "no-cache");
        return null;
    }

    /**
     * 设置封面
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/setAsAlbumCover.do", method = RequestMethod.POST)
    public String setAsAlbumCover(HttpServletRequest req, HttpServletResponse resp) {
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        long photoId = WebUtils.paramLong(req, "photoId", 0);
        String url = WebUtils.param(req, "url", "");
        Album album = albumService.getValidAlbum(albumId);
        if (albumId < 1 || album == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidAlbum!", e);
            }
        }
        if (!authFilter(req, resp)) {
            return null;
        }

        User user = userAuth.getUser(req, resp);

        if (!albumOperateAuth(album.getCreateBy(), album.getClubId(), user.getUid())) {
            this.responseText(resp, false, "您不是会长或该相册创建者!");
            return null;
        }

        //如果传参数photoId，并是不效的照片ID，设置此将照片的URl为封面
        Photo photo = albumService.getPhotoById(photoId, albumId);
        if (photo != null) {
            url = photo.getUrl();
        }
        album.setCover(url);
        album.setUpdateAt(DateUtils.getNow());

        albumService.update(album);

        this.responseText(resp, true);
        resp.setHeader("Cache-Control", "no-cache");

        return null;
    }

    /**
     * 相册、相片操作权限判断 管理员或者创建人才有权限操作数据
     *
     * @param creatorId
     * @param clubId
     * @param operatorId 创建者有可能为0》默认相册
     * @return
     */
    private boolean albumOperateAuth(long creatorId, long clubId, long operatorId) {
        boolean result = false;
        if (memberService.isClubNormalAdmin(operatorId, clubId)) {
            result = true;
        } else {
            if (operatorId > 0) {
                if (creatorId == operatorId) {
                    result = true;
                }
            }
        }
        return result;
    }

    /**
     * 移动照片，增加目标数据，删除原本数据
     */
    private boolean moveAndDeletePhoto(List<Photo> photos, long albumId, long clubId) {
        try {
            for (Photo photo : photos) {

                Photo newPhoto = new Photo();
                newPhoto.setPhotoId(photo.getPhotoId());
                newPhoto.setCreateAt(photo.getCreateAt());
                newPhoto.setCreateBy(photo.getCreateBy());
                newPhoto.setUpdateAt(DateUtils.getNow());
                newPhoto.setUrl(photo.getUrl());
                newPhoto.setStatus(photo.getStatus());
                newPhoto.setName(photo.getName());
                newPhoto.setAlbumId(albumId);


                if (albumService.getTableName(newPhoto).equals(albumService.getTableName(photo))) {
                    albumService.update(newPhoto);
                } else {
                    albumService.create(newPhoto);
                    albumService.deletePhoto(photo);
                }
                ClubPhoto newClubPhoto = albumService.getClubPhoto(clubId, photo.getAlbumId(), photo.getPhotoId());
                if (newClubPhoto != null) {
                    albumService.updateClubPhoto(clubId, photo.getAlbumId(), photo.getPhotoId(), albumId);
                }

            }

        } catch (Exception e) {
            log.error("moveAndDeletePhoto fail!", e);
            return false;
        }
        return true;
    }

    /**
     * 根据车友会ID返回相册列表
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/getAlbumByClubId.do", method = RequestMethod.GET)
    public JSONObject getAlbumByClubId(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        long userId = WebUtils.paramLong(req, "userId", 0);
        Club club = clubService.getValidClub(clubId);
        User user;
        if (userId > 0) {
            user = userService.findUser(userId);
        } else {
            user = userAuth.getUser(req, resp);
        }
        JSONObject json = new JSONObject();
        json.put("clubId", clubId);
        json.put("adminType", clubService.getClubRelationByUser(user, clubId));
        if (club != null) {
            json.put("clubName", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
            JSONArray jsonAlbum = new JSONArray();
            List<Album> listAlbum = albumService.getAllAlbumsByClubId(clubId, 0);
            if (listAlbum != null && !listAlbum.isEmpty()) {
                for (Album album : listAlbum) {
                    JSONObject objAlbum = new JSONObject();
                    JSONArray array = new JSONArray();
                    objAlbum.put("albumName", album.getName());
                    objAlbum.put("albumId", album.getAlbumId());
                    objAlbum.put("photoSize", album.getQuantity());
                    objAlbum.put("coverurlsmall", album.getCover160x120());
                    Pager<Photo> pager = albumService.pagerAllPhotosByAlbumId(album.getAlbumId(), 6, 1);
                    if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
                        for (Photo photo : pager.getResultList()) {
                            JSONObject jsonPhoto = new JSONObject();
                            jsonPhoto.put("urlbig", EncodeUtils.encodeForHTML(photo.getUrl700x(), sourceAgent));
                            jsonPhoto.put("urlsmall", EncodeUtils.encodeForHTML(photo.getUrl160x120(), sourceAgent));
                            array.add(jsonPhoto);
                        }
                    }
                    objAlbum.put("photos", array);
                    jsonAlbum.add(objAlbum);
                    AppUtils.setSuccessCode(json);
                    json.put("data", jsonAlbum);
                }
            }

        } else {
            AppUtils.setDataErrorCode(json, "该车友会ID不存在");
        }
        return json;
    }

    /**
     * 根据相册ID返回相片列表 论坛有调用
     *
     * @throws
     */
    @RequestMapping(value = "/getPhotoByAlbumId.do", method = RequestMethod.GET)
    public void getPhotoByAlbumId(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        int pageSize = WebUtils.paramInt(req, "pageSize", DEFAULT_PAGE_SIZE, 1, 100);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        long userId = WebUtils.paramLong(req, "userId", 0);
        String callback = WebUtils.param(req, "callback", "");
        Album album = albumService.getAlbumById(albumId);
        User user;
        if (userId > 0) {
            user = userService.findUser(userId);
        } else {
            user = userAuth.getUser(req, resp);
        }
        JSONObject json = new JSONObject();
        json.put("albumId", albumId);
        if (album != null) {
            json.put("albumName", EncodeUtils.encodeForHTML(album.getName(), sourceAgent));
            json.put("adminType", clubService.getClubRelationByUser(user, album.getClubId()));
            JSONArray jsonAlbum = new JSONArray();
            Pager<Photo> pager = albumService.pagerAllPhotosByAlbumId(albumId, pageSize, pageNo);
            if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
                for (Photo photo : pager.getResultList()) {
                    JSONObject jsonPhoto = new JSONObject();
                    jsonPhoto.put("urlbig", EncodeUtils.encodeForHTML(photo.getUrl700x(), sourceAgent));
                    jsonPhoto.put("urlsmall", EncodeUtils.encodeForHTML(photo.getUrl160x120(), sourceAgent));
                    jsonPhoto.put("photoId", photo.getPhotoId());
                    jsonPhoto.put("width", photo.getWidth());
                    jsonPhoto.put("height", photo.getHeight());
                    jsonAlbum.add(jsonPhoto);
                }
            }
            json.put("data", jsonAlbum);
            json.put("pageNo", pager.getPageNo());
            json.put("pageCount", pager.getPageCount());
            json.put("pageSize", pager.getPageSize());
            json.put("total", pager.getTotal());
            AppUtils.setSuccessCode(json);
        } else {
            AppUtils.setDataErrorCode(json, "该相册不存在");
        }
        try {
            PrintWriter out = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                out.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json + ")");
            } else {
                out.println(json);
            }
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("getPhotoByAlbumId fail!", ex);
        }
    }

    /**
     * 上传图片接口(APP)
     *
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/uploadPic.do", method = RequestMethod.POST)
    public JSONObject uploadPic(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        User user = userAuth.getUser(req, resp);
        String urls = WebUtils.param(req, "urls", "");
        JSONObject json = new JSONObject();
        if (user != null && user.getUid() > 0) {
            Album album = albumService.getAlbumById(albumId);
            if (album != null) {
                if (memberService.isClubMember(user.getUid(), album.getClubId())) {
                    String[] urlArr = urls.split(",");
                    String result = "";
                    for (String url : urlArr) {

                        String[] arr = url.split("@");
                        Photo photo = new Photo();
                        photo.setAlbumId(albumId);
                        photo.setCreateAt(DateUtils.getNow());
                        photo.setName(arr[0]);
                        photo.setUrl(arr[1]);
                        if (arr.length > 2 && StringUtils.isNotBlank(arr[2])) {
                            String[] whs = arr[2].split("x");
                            if (whs != null && whs.length == 2) {
                                int width = NumberUtils.toInt(whs[0], 0);
                                int height = NumberUtils.toInt(whs[1], 0);
                                photo.setWidth(width);
                                photo.setHeight(height);
                            }
                        }

                        photo.setCreateBy(user.getUid());
                        photo.setStatus(Photo.STATUS_NORMAL);
                        long i = albumService.create(photo);
                        synchronized (album) {
                            albumService.refshAlbumPhotos(albumId, arr[1]);
                        }
                        if (i < 1) {
                            result += arr[1] + ",";
                        }
                    }
                    if (StringUtils.isBlank(result)) {
                        AppUtils.setSuccessCode(json);
                    } else {
                        AppUtils.setDataErrorCode(json, result);
                    }
                } else {
                    AppUtils.setPermissionsError(json, "只有该车友会会员才能上传图片哦！");
                }
            } else {
                AppUtils.setDataErrorCode(json, "该相册ID不存在");
            }
        } else {
            AppUtils.setNoLoginCode(json);
        }
        return json;
    }

    /**
     * 创建(修改)相册接口
     *
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/updateSaveAlbum.do", method = RequestMethod.POST)
    public JSONObject updateSaveAlbum(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long albumId = WebUtils.paramLong(req, "albumId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        User user = userAuth.getUser(req, resp);
        String name = WebUtils.param(req, "name", "");
        JSONObject json = new JSONObject();
        int code = -1;
        String message;
        if (user != null && user.getUid() > 0) {
            if (clubService.getValidClub(clubId) != null) {
                if (memberService.isClubMember(user.getUid(), clubId)) {
                    if (StringUtils.isBlank(name)) {
                        code = AppUtils.STATUS_DATA_ERROR;
                        message = "相册名称不能为空";
                    } else if (!name.matches(Regex.chineseNumAbc.value)) {
                        code = AppUtils.STATUS_DATA_ERROR;
                        message = "请输入汉字、数字或者字母";
                    } else if (name.length() > 20) {
                        code = AppUtils.STATUS_DATA_ERROR;
                        message = "请使用长度为1～20个字符的数字、字母或者汉字";
                    } else {
                        if (albumId > 0) {
                            //update
                            Album album = albumService.getAlbumById(albumId);
                            if (album != null) {
                                if (!albumOperateAuth(album.getCreateBy(), clubId, user.getUid())) {
                                    code = AppUtils.STATUS_PERMISSIONS_ERROR;
                                    message = "您不是会长或创建者，无法修改相册信息";
                                } else {
                                    album.setName(name);
                                    album.setUpdateAt(DateUtils.getNow());
                                    long i = albumService.update(album);
                                    if (i > 0) {
                                        code = 0;
                                        message = "相册修改成功";
                                    } else {
                                        message = "相册修改失败";
                                    }
                                }
                            } else {
                                code = AppUtils.STATUS_DATA_ERROR;
                                message = "该相册ID不存在";
                            }
                        } else {
                            //add
                            long i = albumService.createAlbum(clubId, user.getUid(), name, Album.ISDEFAULT_NO);
                            if (i > 0) {
                                code = 0;
                                message = "相册创建成功";
                                json.put("albumId", i);
                            } else {
                                message = "相册创建失败";
                            }
                        }
                    }
                } else {
                    code = AppUtils.STATUS_PERMISSIONS_ERROR;
                    message = "您不是该车友会会员，请先加入该车友会";
                }
            } else {
                code = AppUtils.STATUS_DATA_ERROR;
                message = "该车友会ID不存在";
            }
        } else {
            code = AppUtils.STATUS_NOLOGIN_ERROR;
            message = "用户未登录，请登录";
        }
        json.put("code", code);
        json.put("message", message);
        return json;
    }

    /**
     * 根据用户ID获取车友会相册数据
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/getAlbumByUserId.do", method = RequestMethod.GET)
    public void getPhotoByUserId(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long userId = WebUtils.paramLong(req, "userId", 0);
        String callback = WebUtils.param(req, "callback", "");
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", DEFAULT_PAGE_SIZE, 1, 100);
        JSONObject json = new JSONObject();
        json.put("userId", userId);
        if (userId > 0) {
            List<ClubMember> listMember = memberService.listClubMemberByUser(userId);
            if (listMember != null && !listMember.isEmpty()) {
                JSONArray clubArr = new JSONArray();
                for (ClubMember member : listMember) {
                    JSONObject objArr = new JSONObject();
                    Pager<Album> pager = albumService.pagerAllAlbumByClubId(member.getClubId(), pageSize, pageNo);
                    if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
                        JSONArray array = new JSONArray();
                        for (Album album : pager.getResultList()) {
                            JSONObject obj = new JSONObject();
                            obj.put("albumId", album.getAlbumId());
                            obj.put("albumName", album.getName());
                            obj.put("cover", album.getCover());
                            obj.put("defaultAlbum", album.getIsDefault());
                            array.add(obj);
                        }
                        objArr.put("clubId", member.getClubId());
                        objArr.put("data", array);
                        objArr.put("total", pager.getTotal());
                        objArr.put("pageNo", pager.getPageNo());
                        objArr.put("pageSize", pager.getPageSize());
                        objArr.put("pageCount", pager.getPageCount());
                    }
                    clubArr.add(objArr);
                    json.put("data", clubArr);
                }
            } else {
                json.put("message", "该用户没加入车友会");
            }
        } else {
            json.put("message", "参数错误");
        }
        try {
            PrintWriter print = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toJSONString() + ")");
            } else {
                print.println(json.toJSONString());
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("getPhotoByAlbumId fail!", ex);
        }
    }

    /**
     * 根据车友会ID获取相册列表
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getAlbumJsonByClub", method = RequestMethod.GET)
    public void listAlbumByClub(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            WebUtils.setEncoding(request, response);
            long clubId = WebUtils.paramLong(request, "clubId", 0);
            int pageNo = WebUtils.paramInt(request, "pageNo", 1);
            int pageSize = WebUtils.paramInt(request, "pageSize", 10, 1, 100);
            String callback = WebUtils.param(request, "callback", "");
            JSONObject object = new JSONObject();
            if (clubId < 1) {
                object.put("code", -1);
                object.put("message", "车友会ID不能为空");
            } else {
                Pager<Album> pager = albumService.pagerLoadAlbumsByClubId(clubId, pageNo, pageSize);
                albumService.loadPhotoByAlbumsLimit(pager.getResultList(), 6);
                JSONArray array = new JSONArray();
                if (pager.getResultList() != null) {
                    for (Album a : pager.getResultList()) {
                        array.add(albumService.parseAlbumJSON(a));
                    }
                }
                object.put("data", array);
                object.put("pageNo", pager.getPageNo());
                object.put("pageSize", pager.getPageSize());
                object.put("pageCount", pager.getPageCount());
                object.put("total", pager.getTotal());
                object.put("code", 0);
            }
            out = response.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                out.println(callback + "(" + object + ")");
            } else {
                out.println(object);
            }
            out.flush();
        } catch (IOException ex) {
            log.error("listAlbumByClub fail!", ex);
        } finally {
            out.close();
        }
    }

    /**
     * WAP相册列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/wap/list", method = RequestMethod.GET)
    public String albumWap(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getClub(clubId);
        if (clubId < 1 || club == null) {
            try {
                response.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail!", ex);

            }
        }

        Pager<Album> pager = albumService.pagerLoadAlbumsByClubId(clubId, 1, 3);
        albumService.loadPhotoByAlbumsLimit(pager.getResultList(), 6);
        request.setAttribute("isMore", pager.getPageNo() < pager.getPageCount());
        request.setAttribute("pager", pager);
        request.setAttribute("clubId", clubId);
        request.setAttribute("club", club);
        return "/template/wap/album/album_list";
    }

    /**
     * WAP单独相册页
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/wap/photo", method = RequestMethod.GET)
    public String albumPhotoWap(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getClub(clubId);
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        Album album = albumService.getAlbumById(albumId);
        if (clubId < 1 || albumId < 1 || album == null || club == null) {
            try {
                response.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--getAlbumById!", ex);
            }
        }
        Pager<Photo> pager = albumService.pagerAllPhotosByAlbumId(albumId, 12, 1);
        request.setAttribute("isMore", pager.getPageNo() < pager.getPageCount());
        request.setAttribute("pager", pager);
        request.setAttribute("album", album);
        request.setAttribute("club", club);
        request.setAttribute("clubId", clubId);
        return "/template/wap/album/album";
    }

    @RequestMapping(value = "/wap/photoDetail", method = RequestMethod.GET)
    public String albumPhotoDetailWap(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        long photoId = WebUtils.paramLong(request, "photoId", 0);
        Album album = albumService.getAlbumById(albumId);
        Photo photo = albumService.getPhotoById(photoId, albumId);
        List<Photo> list = albumService.getAllPhotosByAlbumId(albumId);
        if (clubId < 1 || albumId < 1 || album == null || photo == null) {
            try {
                response.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail!", ex);
            }
        }
        request.setAttribute("total", album.getQuantity());
        request.setAttribute("index", list.indexOf(photo));
        request.setAttribute("album", album);
        request.setAttribute("photo", photo);
        request.setAttribute("clubId", clubId);
        return "/template/wap/album/photo";
    }

    /**
     * 根据相册ID获取图片(WAP相册终端页用)
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getPhotoUrl", method = RequestMethod.GET)
    public void getPhotoUrl(HttpServletRequest request, HttpServletResponse response) {
        long albumId = WebUtils.paramLong(request, "productId", 0);
        String callback = WebUtils.param(request, "callback", "");
        int index = WebUtils.paramInt(request, "index", 0);
        int pageSize = 10;
        int start = index > pageSize ? (index - pageSize) : 0;
        int end = index + 10;
        Album album = albumService.getAlbumById(albumId);
        List<Photo> list = albumService.listPhotosByAlbumId(albumId, start, end);
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        for (int i = 0; i < list.size(); i++) {
            Photo photo = list.get(i);
            JSONObject o = new JSONObject();
            o.put("index", start + i);
            o.put("name", photo.getName());
            o.put("url", photo.getUrl400x());
            array.add(o);
        }
        object.put("groupId", albumId);
        object.put("items", array);
        object.put("total", album == null ? 0 : album.getQuantity());
        try {
            PrintWriter out = response.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                out.println(callback + "(" + object + ")");
            } else {
                out.println(object);
            }
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("getPhotoUrl fail!", ex);
        }

    }

    /**
     * 查找相册接口
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/refleshAlbum", method = RequestMethod.POST)
    public void refleshAlbum(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        String callback = WebUtils.param(request, "callback", "");
        JSONObject jsonObject = new JSONObject();
        if (clubService.getValidClub(clubId) == null) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "数据异常,该车友会不存在!");
            this.printMsg(response, jsonObject.toJSONString(), callback);
            return;
        }
        JSONArray array = new JSONArray();
        List<Album> list = albumService.getAllAlbumsByClubId(clubId, 0);
        if (list != null) {
            for (Album album : list) {
                JSONObject o = new JSONObject();
                o.put("name", album.getName());
                o.put("id", album.getAlbumId());
                array.add(o);
            }
        }
        jsonObject.put("code", AppUtils.STATUS_OK);
        jsonObject.put("data", array);
        this.printMsg(response, jsonObject.toJSONString(), callback);
    }

    /**
     * 最新上传
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getLastestPhotos.do", method = RequestMethod.GET)
    public String getLastestPhotos(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEFAULT_PAGE_SIZE);

        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            try {
                response.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidClub!", e);
            }
        }
        List<ClubPhoto> clubPhotos = albumService.listAllPhotoByClub(clubId);

        List<YearMonth> yms = listYmByPhoto(clubPhotos);
        List<Integer> years = getYears(yms);

        int year = WebUtils.paramInt(request, "year", 0);
        int month = WebUtils.paramInt(request, "month", 0);
        Date curDate = DateUtils.getNow();
        Calendar cal = Calendar.getInstance();
        cal.setTime(curDate);
        if (year == 0 || month == 0) {
            year = cal.get(Calendar.YEAR);
            month = cal.get(Calendar.MONTH) + 1;
        }
        List<ClubPhoto> monthClubPhotos = listYMPhoto(year, month, clubPhotos);
        if (monthClubPhotos.isEmpty() && !yms.isEmpty()) {	//当前月没有数据时，出最近有数据的月份
            YearMonth otherYM = yms.get(0);
            monthClubPhotos = listYMPhoto(otherYM.getYear(), otherYM.getMonth(), clubPhotos);
        }

        List<LastestPhoto> lastestPhotos = listPhotoGroup(monthClubPhotos);
        List<LastestPhoto> pageLastestPhotos = pagerPhotoGroup(lastestPhotos, pageNo, pageSize);

        ClubController.setClubStyle(request, clubId);
        request.setAttribute("hasMore", lastestPhotos.size() > (pageNo * pageSize));
        request.setAttribute("pageLastestPhotos", pageLastestPhotos);
        request.setAttribute("curYear", cal.get(Calendar.YEAR));	//现在年份
        request.setAttribute("curMon", cal.get(Calendar.MONTH) + 1);	//现在月份
        request.setAttribute("chooseYear", year);		//选择年份
        request.setAttribute("chooseMon", month);
        request.setAttribute("years", years);
        request.setAttribute("yms", yms);
        request.setAttribute("club", club);
        return "/template/album/photo_lastest";
    }

    /**
     * 加载更多最新相片
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/loadMoreLastestPhotos.do", method = RequestMethod.POST)
    @ResponseBody
    public void loadMoreLastestPhotos(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEFAULT_PAGE_SIZE);
        Club club = clubService.getValidClub(clubId);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (club == null) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "车友会不存在!");
            this.printMsg(response, jsonObject.toJSONString(), callback);
            return;
        }
        int year = WebUtils.paramInt(request, "year", 0);
        int month = WebUtils.paramInt(request, "month", 0);
        List<ClubPhoto> clubPhotos = albumService.listAllPhotoByClub(clubId);
        List<ClubPhoto> monthClubPhotos = listYMPhoto(year, month, clubPhotos);
        List<LastestPhoto> lastestPhotos = listPhotoGroup(monthClubPhotos);
        List<LastestPhoto> pageLastestPhotos = pagerPhotoGroup(lastestPhotos, pageNo, pageSize);

        for (LastestPhoto lastest : pageLastestPhotos) {
            JSONObject o = new JSONObject();
            o.put("createDate", DateUtils.format(lastest.getCreateDate(), "yyyy年MM月dd日"));
            o.put("userId", lastest.getUserId());
            o.put("avatar", WebUtils.face(lastest.getUserId(), DEFAULT_AUTHORPHOTO_SIZE));
            List<Photo> photos = lastest.getPhotos();
            JSONArray photoArray = new JSONArray();
            for (Photo p : photos) {
                JSONObject picJson = new JSONObject();
                picJson.put("url", p.getUrl120x80());
                picJson.put("albumId", p.getAlbumId());
                picJson.put("photoId", p.getPhotoId());
                photoArray.add(picJson);
            }
            o.put("photos", photoArray);
            jsonArray.add(o);
        }
        int hasMore = 0; //没有更多
        if (lastestPhotos.size() > (pageNo * pageSize)) {
            hasMore = 1;
        }
        jsonObject.put("hasMore", hasMore);
        jsonObject.put("data", jsonArray);
        jsonObject.put("code", AppUtils.STATUS_OK);
        this.printMsg(response, jsonObject.toJSONString(), callback);

    }

    /**
     * 假分页查找用户最新上传
     *
     * @param list
     * @param pageNo
     * @param pageSize
     * @return
     */
    private List<LastestPhoto> pagerPhotoGroup(List<LastestPhoto> list, int pageNo, int pageSize) {
        List<LastestPhoto> pagers = new ArrayList<LastestPhoto>();
        int index = (pageNo - 1) * pageSize;
        int endIndex = (pageNo - 1) * pageSize + pageSize;
        int end = endIndex > list.size() ? list.size() : endIndex;
        for (int i = index; i < end; i++) {
            LastestPhoto lastest = list.get(i);
            pagers.add(lastest);
        }

        return pagers;
    }

    /**
     * 根据日期，用户分组获取图片信息
     *
     * @param list
     * @return
     */
    private List<LastestPhoto> listPhotoGroup(List<ClubPhoto> list) {
        List<LastestPhoto> lastestPhotos = new ArrayList<LastestPhoto>();
        for (ClubPhoto clubPhoto : list) {
            Photo photo = albumService.getPhotoById(clubPhoto.getPhotoId(), clubPhoto.getAlbumId());
            Date createDate = clubPhoto.getCreateAt();
            long userId = clubPhoto.getCreateBy();
            List<Photo> photos = new ArrayList<Photo>();
            photos.add(photo);

            LastestPhoto addItem = new LastestPhoto(createDate, userId, photos);

            if (lastestPhotos.isEmpty()) {
                lastestPhotos.add(addItem);
            } else {
                int index = -1; //新增图片插入位置
                for (int i = 0; i < lastestPhotos.size(); i++) {
                    LastestPhoto original = lastestPhotos.get(i);
                    if (addItem.equals(original)) {
                        index = i;
                        break;
                    }
                }
                if (index == -1) {	//不存在直接插入
                    lastestPhotos.add(addItem);
                } else {			//存在，添加
                    lastestPhotos.get(index).add(photo);
                }
            }
        }

        return lastestPhotos;

    }

    /**
     * 获取指定月份的所有图片
     *
     * @param year
     * @param month
     * @param list
     * @return
     */
    private List<ClubPhoto> listYMPhoto(int year, int month, List<ClubPhoto> list) {
        List<ClubPhoto> monthPhotos = new ArrayList<ClubPhoto>();

        for (ClubPhoto clubPhoto : list) {
            Date createDate = clubPhoto.getCreateAt();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(createDate);
            if (year == calendar.get(Calendar.YEAR) && month == (calendar.get(Calendar.MONTH) + 1)) {
                monthPhotos.add(clubPhoto);
            }
        }
        return monthPhotos;
    }

    /**
     * 获取有图片上传的年月
     *
     * @param list
     * @return
     */
    private List<YearMonth> listYmByPhoto(List<ClubPhoto> list) {
        List<YearMonth> yms = new ArrayList<YearMonth>();
        Calendar calendar = Calendar.getInstance();
        for (ClubPhoto photo : list) {
            Date createDate = photo.getCreateAt();
            calendar.setTime(createDate);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            YearMonth ym = new YearMonth(year, month);
            if (yms.isEmpty()) {
                yms.add(ym);
            } else {
                if (!yms.contains(ym)) {
                    yms.add(ym);
                }

            }
        }
        return yms;
    }

    /**
     * 获取有图片上传的年份（去除重复）
     *
     * @param list
     * @return
     */
    private List<Integer> getYears(List<YearMonth> list) {
        List<Integer> years = new ArrayList<Integer>();
        for (YearMonth yearMonth : list) {
            int year = yearMonth.getYear();
            if (!years.contains(year)) {
                years.add(year);
            }
        }
        return years;
    }

    /**
     * 根据相册id加载图片
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/listPhtotosByAlbumId.do", method = RequestMethod.POST)
    @ResponseBody
    public void listPhtotosByAlbumId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long albumId = WebUtils.paramLong(request, "albumId", 0);

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        List<Photo> list = albumService.getAllPhotosByAlbumId(albumId);
        for (Photo p : list) {
            JSONObject tempObject = new JSONObject();
            tempObject.put("bigUrl", p.getUrl700x());
            tempObject.put("smallUrl", p.getUrl120x80());
            tempObject.put("photoId", p.getPhotoId());
            jsonArray.add(tempObject);

        }
        jsonObject.put("data", jsonArray);
        jsonObject.put("code", AppUtils.STATUS_OK);
        this.printMsg(response, jsonObject.toJSONString(), callback);
    }

    /**
     * 首次加载图片信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getPhotoById.do", method = RequestMethod.POST)
    @ResponseBody
    public void getPhotoById(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        long photoId = WebUtils.paramLong(request, "photoId", 0);
        long userId = WebUtils.paramLong(request, "userId", 0);

        //图片
        JSONObject jsonObject = new JSONObject();
        Photo photo = albumService.getPhotoById(photoId, albumId);
        if (photo == null) {	//图片不存在，无数据返回
            this.printMsg(response, jsonObject.toJSONString(), callback);
            return;
        }
        JSONObject picJson = photo.toJson();
        picJson.put("createDate", DateUtils.format(photo.getCreateAt(), "yyyy年MM月dd日"));
        picJson.put("avatar", WebUtils.face(photo.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
        picJson.put("userName", userService.getNickNameByUserId(photo.getCreateBy()));
        //点赞
        JSONObject picParasie = new JSONObject();
        boolean isParasie = false; //是否点赞
        boolean isSetAlbumCover = false;
        boolean isDeletePhoto = false;
        if (userId > 0) {
            Album album = albumService.getAlbumById(albumId);
            //用户登录 是否点赞
            PhotoPraise photoPraise = photoPraiseService.getPhotoPraise(userId, photoId);
            if (photoPraise != null) {
                isParasie = true;
            }
            //用户登录设置封面，删除图片权限
            if (albumOperateAuth(album.getCreateBy(), album.getClubId(), userId)) {
                isSetAlbumCover = true;
            }
            if (albumOperateAuth(photo.getCreateBy(), album.getClubId(), userId)) {
                isDeletePhoto = true;
            }
        }
        picJson.put("isSetAlbumCover", isSetAlbumCover);
        picJson.put("isDeletePhoto", isDeletePhoto);

        picParasie.put("isParasie", isParasie);

        Pager<User> userPager = photoPraiseService.getPraiseUserList(photoId, DEFAULT_PAGE_NUM_DETAIL, DEFAULT_PAGE_SIZE_DETAIL);
        if (userPager != null) {
            int total = userPager.getTotal();
            picParasie.put("total", total);
            List<User> userList = userPager.getResultList();
            JSONArray parasieArray = new JSONArray();
            if (userList != null) {
                for (User user : userList) {
                    JSONObject praiseObject = new JSONObject();
                    long praiseUserId = user.getUid();
                    praiseObject.put("userId", praiseUserId);
                    praiseObject.put("avatar", WebUtils.face(praiseUserId, DEFAULT_AUTHORPHOTO_SIZE));
                    parasieArray.add(praiseObject);
                }
            }
            picParasie.put("parasies", parasieArray);
        }
        //回复
        JSONObject picReply = new JSONObject();
        int needToViewUrl = WebUtils.paramInt(request, "needToViewUrl", 0);

        Pager<PhotoReply> pagerReplies = photoReplyService.pagerPhotoReplyByPhotoId(photoId, 1, DEFAULT_PAGE_NUM_DETAIL, DEFAULT_PAGE_SIZE);
        if (pagerReplies != null) {
            int total = pagerReplies.getTotal();
            picReply.put("total", total);
            picReply.put("pageCount", pagerReplies.getPageCount());
            picReply.put("pageNo", DEFAULT_PAGE_NUM_DETAIL);
            picReply.put("pageSize", DEFAULT_PAGE_SIZE);
            List<PhotoReply> replies = pagerReplies.getResultList();
            JSONArray replyArray = new JSONArray();
            if (replies != null) {
                for (PhotoReply reply : replies) {
                    JSONObject replyObject = new JSONObject();
                    long replyUserId = reply.getCreateBy();
                    replyObject.put("userId", replyUserId);
                    replyObject.put("nickName", userService.getNickNameByUserId(replyUserId));
                    replyObject.put("postToPhotoReplyId", reply.getPhotoReplyId());
                    long postToUserId = reply.getPostToUserId();
                    replyObject.put("postToUserId", postToUserId);
                    replyObject.put("postToNickName", userService.getNickNameByUserId(postToUserId));
                    replyObject.put("avatar", WebUtils.face(replyUserId, DEFAULT_AUTHORPHOTO_SIZE));
                    replyObject.put("niceTime", DateUtils.getFormatedTime(reply.getCreateAt()));
                    String content;
                    if (needToViewUrl == 1) {
                        content = WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(reply.getContent()));
                    } else {
                        content = WebUtils.transformToBBSFace(reply.getContent());
                    }
                    replyObject.put("content", content);
                    replyArray.add(replyObject);
                }
            }

            picReply.put("replyList", replyArray);
        }

        jsonObject.put("picInfo", picJson);
        jsonObject.put("picParasie", picParasie);
        jsonObject.put("picReply", picReply);
        jsonObject.put("code", AppUtils.STATUS_OK);
        this.printMsg(response, jsonObject.toJSONString(), callback);

    }

    /**
     * 发表评论
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/replyPhoto.do", method = RequestMethod.POST)
    @ResponseBody
    public void replyPhoto(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        long photoId = WebUtils.paramLong(request, "photoId", 0);
        String content = WebUtils.param(request, "content", "");
        long postToPhotoReplyId = WebUtils.paramLong(request, "postToPhotoReplyId", 0);
        JSONObject jsonObject = new JSONObject();
        Photo photo = albumService.getValidPhoto(photoId, albumId);
        if (photo == null) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "评论的照片不存在");
            this.printMsg(response, jsonObject.toJSONString(), callback);
            return;
        }
        //被回复的评论是否存在
        PhotoReply pr = null;
        if (postToPhotoReplyId > 0) {
            pr = photoReplyService.findPhotoReplyById(postToPhotoReplyId, photoId);
            if (pr == null) {
                jsonObject.put("code", AppUtils.STATUS_FAIL);
                jsonObject.put("message", "被回复的评论不存在");
                this.printMsg(response, jsonObject.toJSONString(), callback);
                return;
            }
        }
        if (StringUtils.isEmpty(content)) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "评论内容不可以为空");
            this.printMsg(response, jsonObject.toJSONString(), callback);
            return;
        }
        if (StringUtils.length(content) > 150) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "评论内容长度不可以超过150");
            this.printMsg(response, jsonObject.toJSONString(), callback);
            return;
        }
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "用户没登录");
            this.printMsg(response, jsonObject.toJSONString(), callback);
            return;
        }

        //设置照片评论对象
        PhotoReply photoReply = new PhotoReply();
        photoReply.setAlbumId(albumId);
        photoReply.setContent(content);
        photoReply.setCreateAt(new Date());
        photoReply.setCreateBy(user.getUid());
        photoReply.setPhotoId(photoId);
        photoReply.setPostToPhontoReplyId(postToPhotoReplyId);
        if (postToPhotoReplyId == 0) {
            photoReply.setPostToUserId(photo.getCreateBy());	//直接回复评论的上传者
        } else {//评论照片者
            photoReply.setPostToUserId(pr.getCreateBy());
        }
        photoReply.setStatus(PhotoReply.STATUS_NORMAL);
        //增加照片评论
        long id = photoReplyService.createPhotoReply(photoReply);
        if (id <= 0) {
            jsonObject.put("code", AppUtils.STATUS_FAIL);
            jsonObject.put("message", "评论失败");
            this.printMsg(response, jsonObject.toJSONString(), callback);
            return;
        }
        //照片评论数+1
        photoReplyService.updatePhotoClunt(photoId, albumId, 1);
        JSONObject successObj = photoReply.toJsonEncodeHtml();
        successObj.put("userId", photoReply.getCreateBy());
        successObj.put("nickName", userService.getNickNameByUserId(user.getUid()));
        successObj.put("postToUserName", userService.getNickNameByUserId(photoReply.getPostToUserId()));
        successObj.put("userAvatar", WebUtils.face(photoReply.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
        successObj.put("time", DateUtils.format(photoReply.getCreateAt(), "MM-dd HH:mm"));
        successObj.put("showCreateDate", DateUtils.format(photoReply.getCreateAt(), "yyyy-MM-dd"));
        successObj.put("showContent", WebUtils.transformToBBSFace(photoReply.getContent()));
        successObj.put("code", AppUtils.STATUS_OK);
        successObj.put("message", "评论成功");
        //发送到审核平台
        censorPhotoReplyService.notifyCensorSystemCreate(request, photoReply);
        this.printMsg(response, successObj.toJSONString(), callback);
        //收到的回复发送
        photoReplyService.setJson4BipToListReply(photoReply, photo);
    }

    /**
     * 图片终端页（评论翻页请求）
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/turnPageNo.do", method = RequestMethod.POST)
    @ResponseBody
    public void turnPageNo(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        long photoId = WebUtils.paramLong(request, "photoId", 0);
        JSONObject picReply = new JSONObject();
        int needToViewUrl = WebUtils.paramInt(request, "needToViewUrl", 0);

        Photo photo = albumService.getPhotoById(photoId, albumId);
        if (photo == null) {	//图片不存在，无数据返回
            picReply.put("code", AppUtils.STATUS_FAIL);
            picReply.put("message", "图片不存在");
            this.printMsg(response, picReply.toJSONString(), callback);
            return;
        }

        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEFAULT_PAGE_SIZE);

        Pager<PhotoReply> pagerReplies = photoReplyService.pagerPhotoReplyByPhotoId(photoId, 1, pageNo, pageSize);
        if (pagerReplies != null) {
            int total = pagerReplies.getTotal();
            picReply.put("total", total);
            picReply.put("pageCount", pagerReplies.getPageCount());
            picReply.put("pageNo", pageNo);
            picReply.put("pageSize", pageSize);
            List<PhotoReply> replies = pagerReplies.getResultList();
            JSONArray replyArray = new JSONArray();
            if (replies != null) {
                for (PhotoReply reply : replies) {
                    JSONObject replyObject = new JSONObject();
                    long replyUserId = reply.getCreateBy();
                    replyObject.put("userId", replyUserId);
                    replyObject.put("nickName", userService.getNickNameByUserId(replyUserId));
                    replyObject.put("postToPhotoReplyId", reply.getPhotoReplyId());
                    long postToUserId = reply.getPostToUserId();
                    replyObject.put("postToUserId", postToUserId);
                    replyObject.put("postToNickName", userService.getNickNameByUserId(postToUserId));
                    replyObject.put("avatar", WebUtils.face(replyUserId, DEFAULT_AUTHORPHOTO_SIZE));
                    replyObject.put("niceTime", DateUtils.getFormatedTime(reply.getCreateAt()));
                    String content;
                    if (needToViewUrl == 1) {
                        content = WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(reply.getContent()));
                    } else {
                        content = WebUtils.transformToBBSFace(reply.getContent());
                    }
                    replyObject.put("content", content);
                    replyArray.add(replyObject);
                }
            }

            picReply.put("replyList", replyArray);
        }
        picReply.put("code", AppUtils.STATUS_OK);
        this.printMsg(response, picReply.toJSONString(), callback);

    }

    /**
     * 点赞
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/doPraise.do", method = RequestMethod.POST)
    public void doPraise(HttpServletRequest request, HttpServletResponse response) {
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            printErrorMsg(response, "您还没有登陆", null);
            return;
        }
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        long photoId = WebUtils.paramLong(request, "photoId", 0);
        int isPraise = WebUtils.paramInt(request, "isPraise", -1);
        if (isPraise == -1 || albumId == 0 || photoId == 0) {
            printErrorMsg(response, "参数出错！", null);
            return;
        }
        int praiseStatus = PhotoPraise.STATUS_UNPRAISE;
        if (isPraise == 1) {
            praiseStatus = PhotoPraise.STATUS_PRAISE;
        }
        photoPraiseService.doPraise(user.getUid(), photoId, albumId, praiseStatus);
        printSuccessMsg(response, "操作成功", null, null);
    }

    /**
     * 获取更多点赞用户
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/getPraiseUserList.do", method = RequestMethod.GET)
    public void getPraiseUserList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        JSONObject jsonObject = new JSONObject();
        long photoId = WebUtils.paramLong(request, "photoId", 0);
        int pageNo = WebUtils.paramInt(request, "pageNo", DEFAULT_PAGE_NUM_DETAIL);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEFAULT_PRAISE_PAGE_SIZE, 1, 50);
        Pager<User> userPager = photoPraiseService.getPraiseUserList(photoId, pageNo, pageSize);
        if (userPager != null) {
            List<User> userList = userPager.getResultList();
            JSONArray arr = new JSONArray();
            if (userList != null) {
                for (User user : userList) {
                    JSONObject o = new JSONObject();
                    o.put("uid", user.getUid());
                    o.put("nickname", user.getNickname());
                    arr.add(o);
                }
            }
            jsonObject.put("list", arr);
            jsonObject.put("pageCount", userPager.getPageCount());
        }
        printSuccessMsg(response, "点赞用户列表", jsonObject, null);
    }

    /**
     * 下载图片
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/downLoadPhoto.do")
    public String downLoadPhoto(HttpServletRequest request, HttpServletResponse response) {
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        long photoId = WebUtils.paramLong(request, "photoId", 0);
        Photo photo = albumService.getPhotoById(photoId, albumId);
        if (photo == null) {	//图片不存在，
            try {
                response.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--findByactIdClubId!", ex);
            }
        }
        String imageUrl = photo.getUrl();
        String photoName = photo.getName().replaceAll(" ", "");
        OutputStream fos = null;
        try {
            photoName = URLEncoder.encode(photoName, "UTF-8");
            URL url = new URL(imageUrl);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            fos = response.getOutputStream();
            byte[] buffer = new byte[1204];
            int byteread;
            while ((byteread = inStream.read(buffer)) != -1) {
                fos.write(buffer, 0, byteread);
            }
            fos.flush();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(photoName.getBytes(), "UTF-8"));
        } catch (IOException e) {
            log.error("download photo fail--IOException!", e);
        } finally {
            try {
                if (null != fos) {
                    fos.close();
                }
            } catch (IOException e) {
                log.error("download photo fail--IOException 2!", e);
            }
        }
        return null;
    }

    /**
     * 跳转显示大图页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/showPhoto.do", method = RequestMethod.GET)
    public String showPhoto(HttpServletRequest request, HttpServletResponse response) {
        long photoId = WebUtils.paramLong(request, "photoId", 0);
        long albumId = WebUtils.paramLong(request, "albumId", 0);
        Album album = albumService.getValidAlbum(albumId);
        long clubId = 0;
        if (album != null) {
            clubId = album.getClubId();
        }
        Club club = clubService.getValidClub(clubId);
        Photo photo = albumService.getPhotoById(photoId, albumId);
        if (album == null || club == null || photo == null) {
            try {
                response.sendError(404);
                return null;
            } catch (Exception e) {
                log.error("redirect to error page fail--getValidClub!", e);
            }
        }
        request.setAttribute("club", club);
        request.setAttribute("photo", photo);
        return "/template/album/photo_show";

    }
}
